<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/11/17
 * Time: 12:29 PM
 */
declare(strict_types=1);


namespace application\module\admin\controller;


use application\module\admin\addon\Addon;
use wshore\core\Response;
use wshore\core\Storage;
use wshore\throws\DatabaseException;

class install
{

    public function addon(string $name, string $unlock = '')
    {
        $lock = WS_PATH_RUNTIME . 'lock/addon_' . $name;
        if ($unlock) {
            if ($unlock === SECRET_KEY) {
                is_file($lock) and unlink($lock);
                Response::success("unlock '$name' success");
            } else {
                echo $lock;
                Response::failure("unlock '$name' failed");
            }
        } else {
            is_file($lock) and Response::failure("Addon '$name' locked");
            $classname = '\\application\\module\\admin\\addon\\' . $name;
            if (class_exists($classname)) {
                /** @var Addon $instance */
                $instance = new $classname();
                try {
                    $instance->install();
                    Storage::touch($lock);
                    Response::success("Addon '$name' install done");
                } catch (DatabaseException $exception) {
                    Response::failure("Install [$name] failed:" . $exception->getMessage());
                }
            } else {
                Response::failure("Addon '$name' not exist");
            }
        }
    }

}